<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Title</title>
	<style>
		table{
			width:100%;
		}
		table td{
			border:1px solid green;
			text-align: center;
		}
	</style>
</head>
<body>
<form name="myForm">
	<p>用户名：<input type="text" name="userName"></p>
	<p>
		是否已婚：<input name="isJieHun" type="radio" value="1">是
		<input checked  name="isJieHun" type="radio" value="0">否
	</p>
	<p>所在城市：
		<select name="city">
			<option value="1">北京</option>
			<option value="2">上海</option>
			<option value="3">天津</option>
			<option value="4">成都</option>
			<option value="5">武汉</option>
		</select>
	</p>
	<p>爱好：
		<input type="checkbox" name="hobby" value="1">学习
		<input type="checkbox" name="hobby" value="2">看书
		<input type="checkbox" name="hobby" value="3">游泳
	</p>
	<p>
		<button>添加</button>
	</p>
	
</form>
<hr/>
<div id="root">

</div>
</body>
<script>
	const btn = document.querySelector("button");
	const cityEnum = {
		1:"北京",
		2:"上海",
		3:"天津",
		4:"成都",
		5:"武汉"
	}
	const hobbyEnum = {
		1:"学习",
		2:"看书",
		3:"游泳",
	}
	btn.onclick = function(e){
		e.preventDefault();
		// console.log([...document.myForm.hobby].filter(item=>item.checked).map(item=>item.value))
		const xhr = new XMLHttpRequest();
		xhr.open("post","http://zhangpeiyue.com/userList");
		xhr.setRequestHeader("Content-Type","application/json");
		xhr.send(JSON.stringify({
			userName:document.myForm.userName.value.trim(),
			isJieHun:document.myForm.isJieHun.value.trim(),
			city:document.myForm.city.value.trim(),
			hobby:[...document.myForm.hobby].filter(item=>item.checked).map(item=>item.value)
		}));
		xhr.onload = function(){
			console.log(xhr.response);
			getUserList();
		}
	}
	getUserList();
	function getUserList(){
		const xhr = new XMLHttpRequest();
		xhr.responseType = "json";
		xhr.open("get","http://zhangpeiyue.com/userList");
		xhr.send();
		xhr.onload = function(){
			// console.log(xhr.response);
			root.innerHTML = (`
				<table>
		            <tr>
		                <td>id</td>
		                <td>名字</td>
		                <td>是否已婚</td>
		                <td>城市</td>
		                <td>爱好</td>
		                <td>操作</td>
		            </tr>
		            ${xhr.response.reverse().map(item=>(`
		                <tr>
			                <td>${item.id}</td>
			                <td>${item.userName}</td>
			                <td>${item.isJieHun==="0"?"未婚":"已婚"}</td>
			                <td>${cityEnum[item.city]}</td>
			                <td>${item.hobby.map(item=>hobbyEnum[item]).join("、")}</td>
			                <td><button onclick="delUserById('${item.id}')">删除</button></td>
			            </tr>
		            `)).join("")}
		        </table>
			`)
		}
	}
	function delUserById(id){
		if(window.confirm("您确定要删除该条信息吗？")){
			const xhr = new XMLHttpRequest();
			xhr.responseType = "json";
			xhr.open("delete","http://zhangpeiyue.com/userList/"+id);
			xhr.send();
			xhr.onload = function(){
				getUserList();
			}
		}
		
	}
</script>
</html>